import React, { useState, useEffect } from 'react';
import { Layout as AntLayout, Menu, Avatar, Dropdown, Divider, Badge } from 'antd';
import { Link, useLocation, useNavigate } from 'react-router-dom';
import {
  HomeOutlined,
  LineChartOutlined,
  CalculatorOutlined,
  TrophyOutlined,
  CheckSquareOutlined,
  UserOutlined,
  LogoutOutlined,
  GlobalOutlined,
  ThunderboltOutlined,
  FireOutlined
} from '@ant-design/icons';
import { useUserStore } from '../store/userStore';

const { Header, Content, Sider, Footer } = AntLayout;

const Layout: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const { user, logout } = useUserStore();
  const location = useLocation();
  const navigate = useNavigate();
  const [showRedDot, setShowRedDot] = useState(localStorage.getItem('showRedDotEnvironmental') === 'true');

  // 初始化时检查localStorage中的绿点状态
  useEffect(() => {
    // 定义用于环保任务红点状态的key
    const RED_DOT_STORAGE_KEY = 'showRedDotEnvironmental';
    
    // 检查并初始化红点状态
    const initRedDotStatus = () => {
      console.log('Layout: 初始化红点状态');
      // 如果localStorage中没有存储红点状态，默认显示红点
      if (localStorage.getItem(RED_DOT_STORAGE_KEY) === null) {
        localStorage.setItem(RED_DOT_STORAGE_KEY, 'true');
        setShowRedDot(true);
        console.log('Layout: localStorage中无红点状态，设置为显示');
      } else {
        const status = localStorage.getItem(RED_DOT_STORAGE_KEY) === 'true';
        setShowRedDot(status);
        console.log('Layout: 从localStorage获取红点状态:', status);
      }
    };

    const handleStorageChange = () => {
      const status = localStorage.getItem(RED_DOT_STORAGE_KEY) === 'true';
      console.log('Layout: 检测到storage变化，更新红点状态为:', status);
      setShowRedDot(status);
    };

    // 初始化红点状态
    initRedDotStatus();

    // 添加事件监听器
    window.addEventListener('storage', handleStorageChange);

    // 清理事件监听器
    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  const handleLogout = () => {
    logout();
    navigate('/login');
  };

  const userMenu = (
    <Menu>
      <Menu.Item key="profile" icon={<UserOutlined />}>
        <Link to="/profile">个人资料</Link>
      </Menu.Item>
      <Menu.Divider />
      <Menu.Item key="logout" icon={<LogoutOutlined />} onClick={handleLogout}>
        退出登录
      </Menu.Item>
    </Menu>
  );

  // 获取当前路由路径
  const currentPath = location.pathname;

  // 侧边菜单项配置
  const menuItems = [
    {
      key: '/dashboard/planet',
      icon: <GlobalOutlined />,
      label: <Link to="/dashboard/planet">我的星球</Link>,
    },
    {
      key: '/dashboard/overview',
      icon: <LineChartOutlined />,
      label: <Link to="/dashboard/overview">生态指数</Link>,
    },
    {
      key: '/dashboard/calculator',
      icon: <CalculatorOutlined />,
      label: <Link to="/dashboard/calculator">碳足迹计算</Link>,
    },
    {
      key: '/dashboard/challenges',
      icon: <FireOutlined />,
      label: <Link to="/dashboard/challenges">个性化挑战</Link>,
    },
    {
      key: '/dashboard/tasks',
      icon: <CheckSquareOutlined />,
      label: (
        <Link to="/dashboard/tasks">
          <Badge dot={showRedDot}>
            环保任务
          </Badge>
        </Link>
      ),
    },
    {
      key: '/dashboard/achievements',
      icon: <TrophyOutlined />,
      label: <Link to="/dashboard/achievements">我的成就</Link>,
    },
    // 分隔线
    {
      type: 'divider' as const,
    },
    // 绿色能量显示
    {
      key: 'green-energy',
      icon: <ThunderboltOutlined style={{ color: '#52c41a' }} />,
      label: (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <span>绿色能量</span>
          <span 
            style={{ 
              backgroundColor: '#52c41a', 
              color: 'white', 
              padding: '0px 8px', 
              borderRadius: 10,
              fontWeight: 'bold',
              fontSize: 13,
              marginLeft: 8
            }}
          >
            {user?.greenEnergy || 0}
          </span>
        </div>
      ),
    },
    // 添加返回首页选项
    {
      type: 'divider' as const,
    },
    {
      key: 'home',
      icon: <HomeOutlined />,
      label: '返回首页',
      onClick: () => {
        navigate('/');
        window.location.reload(); // 确保完全刷新页面
      }
    },
  ];

  return (
    <AntLayout style={{ minHeight: '100vh' }}>
      <Header style={{ 
        display: 'flex', 
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingInline: 20,
        backgroundColor: '#fff',
        boxShadow: '0 2px 8px rgba(0,0,0,0.1)'
      }}>
        <div className="logo" style={{ 
          display: 'flex', 
          alignItems: 'center', 
          gap: 8,
          fontSize: 18,
          fontWeight: 'bold'
        }}>
          <GlobalOutlined style={{ color: '#52c41a', fontSize: 22 }} />
          碳星球
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
          <Dropdown overlay={userMenu} trigger={['click']}>
            <div style={{ cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8 }}>
              <Avatar icon={<UserOutlined />} />
              <span>{user?.username || '用户'}</span>
            </div>
          </Dropdown>
        </div>
      </Header>
      <AntLayout>
        <Sider width={200} style={{ background: '#fff' }}>
          <Menu
            mode="inline"
            selectedKeys={[currentPath]}
            style={{ height: '100%', borderRight: 0 }}
            items={menuItems}
          />
        </Sider>
        <AntLayout style={{ padding: '0 24px 24px' }}>
          <Content
            style={{
              padding: 24,
              margin: 0,
              minHeight: 280,
              background: '#fff',
              borderRadius: 8,
              marginTop: 24
            }}
          >
            {children}
          </Content>
        </AntLayout>
      </AntLayout>
    </AntLayout>
  );
};

export default Layout; 